package com.demo.webapp.kcfinder;

import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.demo.common.ClassLoaderUtils;
import com.demo.webapp.kcfinder.action.Action;
import com.demo.webapp.kcfinder.config.ActionConfig;
import com.demo.webapp.kcfinder.config.InterceptorConfig;
import com.demo.webapp.kcfinder.config.ResultTypeConfig;
import com.demo.webapp.kcfinder.context.ActionContext;
import com.demo.webapp.kcfinder.interceptor.Interceptor;
import com.demo.webapp.kcfinder.result.Result;

/**
 * 对象工厂
 * 该对象用于创建Action、Interceptor、Result等对象
 * 
 * @author ryuu.kk
 *
 */
@SuppressWarnings("rawtypes")
public class ObjectFactory {

	private static final Log LOG = LogFactory.getLog(ObjectFactory.class);
	
	protected ServletContext servletContext;
	
	/**ClassLoader**/
	private ClassLoader classLoader = ClassLoaderUtils.getDefaultClassLoader();
	
	protected Object buildBean(Class clazz, Map extraContext) throws Exception {
		if (LOG.isDebugEnabled()) {
			LOG.debug("create bean class " + clazz.getName());
		}
		return clazz.newInstance();
	}
	
	protected Object buildBean(String className, Map extraContext, boolean injectInternal) throws Exception {
        Class clazz = (Class) getClassInstance(className);
        Object obj = buildBean(clazz, extraContext);
        return obj;
    }
    
    protected Class<?> getClassInstance(String className) throws ClassNotFoundException {
    	if (this.classLoader != null) {
    		return classLoader.loadClass(className);
    	}
    	return ClassLoaderUtils.loadClass(className, this.getClass());
    }
    
    public Action buildAction(ActionConfig actionConfig, ActionContext context) throws Exception {
    	Action action = (Action) buildBean(actionConfig.getActionClass(), actionConfig.getParams(), true);
    	return action;
    }
    
    public Interceptor buildInterceptor(InterceptorConfig config) throws Exception {
    	Interceptor interceptor = (Interceptor) buildBean(config.getClassName(), config.getParams(), true);
    	return interceptor;
    }

    public Result buildResult(ResultTypeConfig config) throws Exception {
    	Result result = (Result) buildBean(config.getClassName(), config.getParams(), true);
    	return result;
    }
    
	public ClassLoader getClassLoader() {
		return classLoader;
	}

	public void setClassLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
	}

	public void init(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}
